from flask import Blueprint, request, current_app,send_file,jsonify,send_from_directory
from utilsapp.mathself import get_speed, GetEnvelope, get_rep, get_csd, GetFFT
from reportlab.pdfgen import canvas
from utilsapp.mysql_con import (
    db_pagelist,
    db_delete,
    db_update,
    db_insert,
    db_list,
)
import os
import time
from utilsapp import utils
from utilsapp.common import assign_value, parsing_data_id, find_str
import json
from datetime import datetime

bluePrint = Blueprint("wavecoll", __name__)
tableName = "wavecoll"


@bluePrint.route("/getlist", methods=["POST"])
def table_list():
    a = request.json
    page = assign_value(a, "page", 1)
    size = assign_value(a, "size", 999)
    scope_id = assign_value(a, "scope_id", 0)
    scoped = parsing_data_id(scope_id, request)
    coll_name = assign_value(a, "coll_name")
    number = assign_value(a, "number")
    sql = """SELECT wc.* ,st.name as type_name,wq.name as acq_name,wq.single_axis,wq.three_axis,st.mode
from wavecoll wc 
LEFT JOIN sensor_type st on st.id = wc.sensor_type
LEFT JOIN waveacq wq on wq.id = wc.waveacq """
    query = f""" where 1=1 """
    if scoped != "":
        query += f" and wc.{scoped} "
    if coll_name != "":
        query += f" and wc.coll_name like '%{coll_name}%' "
    if number != "":
        query += f" and wc.number like '%{number}%' "
    j = db_pagelist(f"{sql}{query}", page, size)
    return j


@bluePrint.route("/add", methods=["POST"])
def device_type_add():
    not_add_model = ["scope_id_list", "acq_name"]
    a = request.json
    add_model = {key: a[key] for key in a if key not in not_add_model}
    return db_insert(tableName, add_model)


@bluePrint.route("/delete", methods=["POST"])
def device_type_delete():
    id = request.json["id"]
    return db_delete(tableName, f"WHERE id=%s", {"id": id})


@bluePrint.route("/edit", methods=["POST"])
def a222():
    id = request.json["id"]
    keys_not_add = [
        "scope_id_list",
        "acq_name",
        "type_name",
        "single_axis",
        "three_axis",
        "mode",
    ]
    addModel = {
        key: request.json[key] for key in request.json if key not in keys_not_add
    }
    return db_update(tableName, addModel, f"WHERE id=%s", {"id": id})


@bluePrint.route("/send/directive", methods=["post"])
def a323():
    message = request.json["message"]
    number = request.json["number"]
    if len(message) > 0:
        current_app.redis.set(f"term_config:{number}", message)
    return utils.ok()


@bluePrint.route("/self", methods=["post"])
def a3231():
    a = request.json
    number = assign_value(a, "number")
    sql = (
        f"SELECT * from selfins where number = '{number}' ORDER BY time desc LIMIT 0,1"
    )
    return db_list(sql)


@bluePrint.route("/ter/list", methods=["post"])
def a23333():
    list = []

    for item in current_app.redis.keys("device*"):
        comp = f"{item[-4:]}_device_s"
        status = 0
        if current_app.redis.exists(comp):
            status = 1
        current_app.redis.keys("device*")
        list.append({"addr": item[-4:], "status": status})

    return utils.ok(list)


@bluePrint.route("/ter/getkey", methods=["post"])
def a13():
    a = request.json
    getkey = assign_value(a, "getkey")
    key = assign_value(a, "key")
    addr = assign_value(a, "addr")
    flag = assign_value(a, "flag", 1)

    list = current_app.redis.get(f"{addr}_{getkey}")

    if list is None:
        str1 = "请求中"
        if current_app.redis.exists(f"{addr}_wave_status"):
            str1 = "波形上报中,请稍后再试"
        return utils.fail(msg=str1)
    else:
        list = list.replace("'", '"')

     
    if flag == 2:
        result = current_app.redis.delete(f"{addr}_{getkey}")
        print("删除状态2", result)
        return utils.ok(msg="响应成功")
    if key == "ver":
        item = json.loads(list)
        res = {
            "type": item[0],
            "hardware": item[1],
            "software": item[2],
            "time": utils.date_to_str(
                utils.str_to_date(item[3] + "000000", fomat="%Y%m%d%H%M%S")
            ),
        }
    elif key == "gate":
        item = json.loads(list)
        res = {"ip": item[0], "name": item[1]}
    elif key == "ipport":
        item = json.loads(list)
        res = {"ip": item[0], "port": item[1]}
    elif key == "addr":
        res = list
    elif key == "sen":
        res = []
        item = json.loads(list)
        for index, it in enumerate(item):
            res.append({"text": f"ch{index + 1}", "value": index + 1, "sen": it})
    elif key == "selfins":
        res = []
        item = json.loads(list)
        for index, it in enumerate(item):
            res.append({"label": index + 1, "value": it})
    elif key == "status":
        res = []
        item = json.loads(list)
        for index, it in enumerate(item):
            res.append({"label": index + 1, "value": it})
    elif key == "com":
        res = {"com": list}
    elif key == "sam":
        item = json.loads(list)
        res = {"fre": item[0], "len": item[1]}

    else:
        res = {key: list}
    return utils.ok(res, msg="请求成功")


@bluePrint.route("/ter/send", methods=["post"])
def as2sfdsa():
    try:
        a = request.json
        addr = assign_value(a, "addr")
        setkey = assign_value(a, "setkey")
        current_app.redis.set(f"{addr}_{setkey}", 1, ex=300)
        return utils.ok(msg="已下发指令")
    except Exception as e:
        print("ter/send", str(e))
        return utils.fail(msg="下发指令失败")


@bluePrint.route("/ter/setkey", methods=["post"])
def a1223():
    try:
        a = request.json
        content = assign_value(a, "content")
        addr = assign_value(a, "addr")
        setkey = assign_value(a, "setkey")
        ex = assign_value(a, "ex", 30)
        if ex and ex > 0:
            current_app.redis.set(f"{addr}_{setkey}", content, ex=ex)
        else:
            current_app.redis.set(f"{addr}_{setkey}", content)

        return utils.ok(msg="响应成功")
    except Exception as e:
        print("ter/setkey", str(e))
        return utils.fail(msg="下发指令失败")


@bluePrint.route("/wave/eig", methods=["post"])
def sxxx():
    try:
        a = request.json
        flag = assign_value(a, "flag")
        addr = assign_value(a, "addr")
        channel = assign_value(a, "channel")
        if flag == 1:
            qry = f"{addr}:{channel}:eige*"
            key_value_pairs = {}
            cursor = "0"
            acc_rms = []
            tem = []
            vel_rms = []
            while cursor != 0:
                cursor, keys = current_app.redis.scan(cursor, match=qry)
                for key in keys:
                    try:
                        value = current_app.redis.get(key)
                        if value is None:
                            return utils.fail(msg="暂无数据")
                        c = json.loads(value)
                        acc_rms.append([c["time"], c["data"]["Z"]["acc_rms"]])
                        vel_rms.append([c["time"], c["data"]["Z"]["vel_rms"]])
                        tem.append([c["time"], c["data"]["tem"]])
                        acc_rms = sorted(acc_rms, key=lambda x: x[0])
                        vel_rms = sorted(vel_rms, key=lambda x: x[0])
                        tem = sorted(tem, key=lambda x: x[0])
                    except (KeyError, json.JSONDecodeError) as e:
                        pass
            key_value_pairs = {"acc_rms": acc_rms, "tem": tem, "vel_rms": vel_rms}
        else:
            qry = f"{addr}:{channel}:Z_wave"
            data = current_app.redis.get(qry)
            if data is None:
                return utils.fail(msg="波形过期，请重新取波")
            data = json.loads(data)
            time = data["time"]
            acc_wave = data["data"]["acc"]["acc_wave"]
            freq = data["data"]["freq"]
            # 计算时间间隔
            time_interval = (1 / freq) * 1000
            # 使用列表生成器来创建波形数据
            wave = [[round(time_interval * i, 3), e] for i, e in enumerate(acc_wave)]
            key_value_pairs = {
                "wave": wave,
                "spec": GetFFT(acc_wave, freq),
                "freq": freq,
                "time": datetime.fromtimestamp(time).strftime("%Y-%m-%d %H:%M:%S"),
            }
        return utils.ok(key_value_pairs)
    except Exception as e:
        print("wave/eig", str(e))
        return utils.fail(msg="下发指令失败")


@bluePrint.route("/delete/key", methods=["post"])
def sxxf():
    key = assign_value(request.json, "key")
    result = current_app.redis.delete(key)
    return utils.ok(msg=f"删除状态{result}")


@bluePrint.route("/getAll", methods=["post"])
def sxx2f():
    a = request.json
    addr = assign_value(a, "addr")
    arr = assign_value(a, "arr")
    ar1 = {
        "Addr":addr
    }
    ar2={
        "1210":"Software version",
        "1610":"sensitivity",
        "3010":"static IP",
        "2410":"Communication mode",
        "2610":"ip,port",
        "1310":"self-checking",
        "2210":"sleep time",
        "1810":"wavePeriod",
        "2c10":"waveFreq,waveLen"
    }
    for item in arr:
        a1 = f"{addr}_{item}"
        ar1[ar2[item]]= current_app.redis.get(a1)
    script_dir = os.path.dirname(os.path.abspath(__name__)) + '/static'
    date = time.strftime("%Y%m%d", time.localtime())
    fileName = f'/upload/{date}'
    filePath = script_dir + fileName + f'ter_{addr}.pdf'
    c = canvas.Canvas(filePath)
    c.drawString(100, 750, "Terminal configuration")
    y = 700
    for key, value in ar1.items():
        c.drawString(100, y, f"{key}: {value}")
        y -= 20
    c.save()
    a1= {
        "data":ar1,
        "filePath":filePath
    }
    return utils.ok(a1)



@bluePrint.route('/viewpdf/<path:filename>', methods=['POST', 'GET'])
def view_file(filename):
    try:
  
        return send_file(filename, mimetype='application/pdf')
    except Exception as e:

        return jsonify({'code': -1, 'msg': '下载异常'+str(e)}), 200